package com.example.design.c.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class DynamicProxyTest {
    public static void main(String[] args) {
        FudaoBan fudaoBan = new FudaoBan();
        IPerson zhaoliu = fudaoBan.getInstance(new ZhaoLiu());
        zhaoliu.findTeacher();
        Method[] methods = zhaoliu.getClass().getDeclaredMethods();
        for(Method method:methods){
            System.out.println(method.getName());
        }
    }
}

interface IPerson {

    void findTeacher();
}

class FudaoBan implements InvocationHandler{

    private IPerson target;

    public IPerson getInstance(IPerson target){
        this.target = target;
        Class<?> clazz = this.target.getClass();
        Class<?>[]  classes = clazz.getInterfaces();
        for(Class<?> c:classes){
            System.out.println("person："+c.getName());
        }
        return (IPerson) java.lang.reflect.Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object result = method.invoke(this.target,args);
        after();
        return result;
    }

    public void before(){
        System.out.println("找到老师前");
    }

    public void after(){
        System.out.println("找到老师后");
    }
}

class ZhaoLiu implements IPerson {

    @Override
    public void findTeacher() {
        System.out.println("赵六找老师");
    }

    public void buy(){
        System.out.println("赵六买教材");
    }
}